package com.gin.kotlin.no_gay_alliance.adapter

import android.content.Context
import android.content.DialogInterface
import android.view.View
import com.gin.kotlin.no_gay_alliance.R
import com.gin.kotlin.no_gay_alliance.app.App
import com.gin.kotlin.no_gay_alliance.base.AbstractBindingRecyclerViewAdapter
import com.gin.kotlin.no_gay_alliance.base.AlertDialogUtils
import com.gin.kotlin.no_gay_alliance.base.MyHandler
import com.gin.kotlin.no_gay_alliance.base.ViewUtils.Companion.visible
import com.gin.kotlin.no_gay_alliance.database.entity.TopicBookmark
import com.gin.kotlin.no_gay_alliance.databinding.ItemTopicBookmarkBinding
import com.gin.kotlin.no_gay_alliance.enums.HandlerMessageWhat
import com.gin.kotlin.no_gay_alliance.utils.TimeUtils.Companion.zdtIntoTextView

class TopicBookmarkAdapter(context: Context, handler: MyHandler) : AbstractBindingRecyclerViewAdapter<ItemTopicBookmarkBinding, TopicBookmark>(context, handler),
    View.OnClickListener {
    override fun onBindViewHolder(holder: ViewHolder<ItemTopicBookmarkBinding>, position: Int, b: ItemTopicBookmarkBinding, dataModel: TopicBookmark) {
        val (_, _, page, floorNumber, _, _, username, remark) = dataModel

        b.tvPageFloor.text = "第${page}页, 第${floorNumber}楼"

        b.tvRemark.visibility = visible(remark)
        b.tvRemark.text = remark

        b.tvUsername.visibility = visible(username)
        b.tvUsername.text = username

        zdtIntoTextView(context, dataModel.timestamp, b.tvTimestamp, getAttrColor(R.attr.textColor))

        b.root.tag = dataModel
        b.root.setOnClickListener(this)

        b.ivDelete.tag = dataModel.id
        b.ivDelete.setOnClickListener(this)
    }

    override fun onClick(v: View?) {
        (v?.tag as? TopicBookmark)?.also { handler.sendMessage(HandlerMessageWhat.PAGE_TO_TOPIC_BOOKMARK, it) }
        (v?.tag as? Long)?.also {id->
            val dao = App.INSTANCE.database.topicBookmarkDao()
            val index = data.map { it.id }.indexOf(id)
            // 弹窗确认删除
            AlertDialogUtils.builder(context, "确认删除书签?", listener = { _, which ->
                if (which == DialogInterface.BUTTON_POSITIVE) {
                    dao.del(id)
                    removeData(index)
                }
            }).show()
        }
    }
}